package com.vshop.service.alast.impl;

import com.alibaba.fastjson.JSON;
import com.vshop.config.dto.StringOutputConstant;
import com.vshop.entity.agatewaytobeijing.querydevice.beijing.response.ResponseQueryDevice;
import com.vshop.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder;
import com.vshop.entity.agatewaytobeijing.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.callback.request.RequestResultCallback;
import com.vshop.entity.callback.response.ResponseResultCallback;
import com.vshop.entity.optimize.cancel.response.CancelResponse;
import com.vshop.entity.optimize.end.response.EndResponse;
import com.vshop.entity.optimize.order.response.OrderResponse;
import com.vshop.entity.optimize.reorder.response.RenewResponse;
import com.vshop.entity.purchase.request.RequestPurchaseService;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import com.vshop.service.alast.UpgradedOrderServicePlanService;
import com.vshop.service.impl.PurchaseLogicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 升级3.0后的：异步订购和异步回调 ：：业务实现处理类
 *
 * @author lm
 * @date 2020/8/19 9:43
 */

@Service
@Slf4j
public class UpgradedOrderServicePlanServiceImpl implements UpgradedOrderServicePlanService {
    @Autowired
    PurchaseLogicService purchaseService;
    @Autowired
    OrderAssistService assistService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    /**
     * 新的：：：：：：：
     * 3.0版本接口：订购套餐业务逻辑处理类
     *
     * @param pur
     * @return
     */
    @Override
    public String purchaseServicePlan(RequestPurchaseService pur) {
        /*未避免同一个订单在遇到异常情况时发生多次没有必要的请求，只要请求到达这边，先去把数据库里面的：service_plan_order_record_t的isRequest值从0变成1，就算有异常也只去记录一次即可*/
        assistService.updateIsRequestByOrder(pur.getDeviceCode(), pur.getOrderNo());

        ResponseQueryDeviceOrder orderData = toBeijingService.queryDeviceOrder(pur.getDeviceCode(), "", "", "", pur.getPartnerCode(), pur.getSecret());

        /*1，先去拿到卡片上面所有订单，匹配赠送套餐（有：判断状态：a，正在使用==提前结束套餐；b==取消套餐；无：继续走第2步）*/
        matchGiveDateNew(orderData, pur);

        /*2,新订要不要开通日程类套餐是个特例。这边对日程类套餐进行特殊处理，不允许订购并立即开通,订购之后也不需要手动开通*/
        String type = matchPackageType(pur);
        if (!StringOutputConstant.CODE_FAIL.equals(type)) {
            /*返回不是FAIL说明套餐是日程类套餐，直接返回新订但是不立即开通*/
            return type;
        }

        /*3,如果type返回的是“FAIL”，需要继续往下走：匹配续订流程*/
        String result = matchRenewOrderNew(orderData, pur);
        if (!StringOutputConstant.CODE_FAIL.equals(result)) {
            /*4，如果result返回的不是“FAIL”，那就可以直接返回续订的结果*/
            return result;
        }

        /*5,如果result返回的是“FAIL”，就继续走新订路*/
        return matchOrderNew(pur);
    }

    /**
     * 优化后新版本：
     * 网关对新订|续订处理结果回调
     *
     * @param callback
     * @return
     */
    @Override
    public String callback(RequestResultCallback callback) {
        String callbackStr;
        try {
            if (null == callback || StringUtils.isBlank(JSON.toJSONString(callback))) {
                log.info("请求报文为空：" + callback);
                return assistService.responseCallbackStr("9999", "请求报文为空");
            }
            callbackStr = JSON.toJSONString(callback);
            log.info("【新订|续订的回调】请求：" + callbackStr);
        } catch (Exception e) {
            log.info("处理【新订|续订的回调】时有异常：" + e);
            return assistService.responseCallbackStr("9999", "程序异常");
        }
        if (StringUtils.isBlank(callback.getCode()) || StringUtils.isBlank(callback.getMessage()) || StringUtils.isBlank(callback.getPayId()) || StringUtils.isBlank(callback.getDeviceCode()) || StringUtils.isBlank(callback.getType())) {
            log.info("主要参数存在不合法");
            /*发送异常邮件*/
            purchaseService.sendToPrivate(callbackStr, "5个必传的参数存在未传情况");
            return assistService.responseCallbackStr("9999", "请求参数不合法");
        }
        //数据库把这条数据取出来
        ServicePlanOrderRecord record = assistService.queryRecord(callback.getPayId().trim(), callback.getDeviceCode().trim());
        if (null == record) {
            log.info("当前数据库没有查到对应的订单数据，有可能是数据库跟环境对应有误！");
            return assistService.responseCallbackStr("9999", "订单回调位置有误，客户端自行查看！");
        }
        if (!StringOutputConstant.CODE_0000.equals(callback.getCode())) {
            log.info("返回code不是成功，一律按照失败处理发邮件");
            //发送异常邮件：
            if (StringOutputConstant.CODE_ZERO.equals(callback.getType())) {
                purchaseService.sendMailForCallback(callback, record, "新订");
            } else {
                purchaseService.sendMailForCallback(callback, record, "续订");
            }
            //记录异常操作到数据库：
            assistService.exceptionDetailsRecord(record.getPartnerCode(), callback.getDeviceCode(), record.getPayId(), record.getOrderNo(), "8", callback.getCode(), callback.getMessage());
            //返回
            return assistService.responseCallbackStr("9999", "接口交互成功,但业务处理失败！");
        }
        //处理的业务类型：0-新订；1-续订,如果既不是0也不是1就说明type指令有误
        if (!callback.getType().equals(StringOutputConstant.CODE_ZERO) && !callback.getType().equals(StringOutputConstant.CODE_ONE)) {
            return assistService.responseCallbackStr("9999", "type指令有误");
        }
        if (StringUtils.isBlank(callback.getOrderId()) || StringUtils.isBlank(callback.getOrderStatus()) || StringUtils.isBlank(callback.getOrderDate()) || StringUtils.isBlank(callback.getTradeTime())) {
            log.info("成功响应时，必须包含订单主要信息");
            return assistService.responseCallbackStr("9999", "请求参数不合法");
        }
        boolean b1 = StringOutputConstant.CODE_TWO.equals(callback.getOrderStatus()) && (StringUtils.isBlank(callback.getActiveDate()) || StringUtils.isBlank(callback.getExpireDate()));
        if (b1) {
            log.info("订单状态是【正在使用】时，必须有激活时间和到期时间");
            return assistService.responseCallbackStr("9999", "请求参数不合法");
        }
        /*去数据库更新数据*/
        Integer upCount;
        try {
            upCount = assistService.updateCallback(callback);
        } catch (Exception e) {
            /*走到这边的有可能是入库时出现了异常*/
            log.info("【新订|续订的回调】数据库入数据库异常：" + e);
            /*记录异常操作到数据库*/
            assistService.exceptionDetailsRecord(record.getPartnerCode(), callback.getDeviceCode(), record.getPayId(), record.getOrderNo(), "9", "9998", "不符合常规的传值导致了入库的异常");
            /*发送异常邮件*/
            purchaseService.sendToPrivate(callbackStr, "传参中肯定有不符合常规的传值导致了入库的异常");
            /*要么回传数据有误，要么就是去数据库查有问题，总之都用这个数据有误请重试响应*/
            return assistService.responseCallbackStr("9998", "数据有误请重试");
        }
        /*数据库更新的结果*/
        if (upCount < 1) {
            /*记录异常操作到数据库*/
            assistService.exceptionDetailsRecord(record.getPartnerCode(), callback.getDeviceCode(), record.getPayId(), record.getOrderNo(), "9", "9998", "数据有误请重试");
            /*发送异常邮件*/
            purchaseService.sendToPrivate(callbackStr, "数据库更新有误");
            /*要么回传数据有误，要么就是去数据库查有问题，总之都用这个数据有误请重试响应*/
            return assistService.responseCallbackStr("9998", "数据有误请重试");
        }

        /*说明数据更新成功，现在应该响应成功的消息回去.根据回调记录去更新数据库记录，这边我们将启用orderNo代替payId作为唯一卡片订单的订购标志*/
        ResponseResultCallback response = new ResponseResultCallback();
        response.setRetCode("0000");
        response.setResultInfo("success");
        response.setPartnerCode(record.getPartnerCode());
        response.setDeviceCode(record.getDeviceCode());
        response.setPayId(record.getOrderNo());
        response.setOrderId(record.getOrderId());
        response.setServicePlanShowName(record.getServicePlanShowName());
        response.setPayUnit(record.getPayUnit());
        response.setPayCurrency(record.getPayCurrency());

        /* 返回给调用者的报文*/
        String jsonString = JSON.toJSONString(response);
        log.info("【新订|续订的回调】响应：success" + ";结果：" + jsonString);
        return jsonString;
    }

    /**
     * 新的：匹配赠送套餐的逻辑
     *
     * @param orderData
     * @param pur
     */
    public void matchGiveDateNew(ResponseQueryDeviceOrder orderData, RequestPurchaseService pur) {
        /*系统异常 响应：{"code":"9999","data":null,"message":null,"success":false}*/
        if (null == orderData || null == orderData.getCode() || StringOutputConstant.CODE_9999.equals(orderData.getCode())) {
            //发送异常邮件：
            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询全部订单", "未查询到任何套餐，请求或相应出现异常！");
            //记录异常操作到数据库：
            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", "9999", "未查询到任何套餐，请求或相应出现异常！");
            log.info(pur.getDeviceCode() + "未查询到任何套餐，请求或相应出现异常！");
            return;
        }
        if (Constant.RET_CODE_0000.equals(orderData.getCode()) && null != orderData.getData() && null != orderData.getData().getPackageOrder() && !orderData.getData().getPackageOrder().isEmpty()) {

            for (DevicePackageOrder tr : orderData.getData().getPackageOrder()) {

                if (StringUtils.isNotBlank(tr.getPackageCode()) && StringUtils.isNotBlank(tr.getOrderId()) && StringUtils.isNotBlank(tr.getOrderStatus())) {

                    //拿着tr.getPackageCode()去数据库查询看看有没有这个赠送套餐的套餐编码
                    Integer c = purchaseService.queryGiveDateOrNot(tr.getPackageCode());
                    log.info(tr.getPackageCode() + "：匹配【赠送套餐】结果是：" + c);
                    //赠送套餐且为未启用状态
                    boolean b1 = (StringOutputConstant.CODE_ONE.equals(tr.getOrderStatus()) && c >= 1);
                    //赠送套餐且为正在使用状态
                    boolean b2 = (StringOutputConstant.CODE_TWO.equals(tr.getOrderStatus()) && c >= 1);
                    if (b1) {
                        log.info(pur.getDeviceCode() + "：有【未启用赠送套餐】：" + tr.getPackageName());
                        //未启用赠送套餐----取消订单
                        CancelResponse cancel = toBeijingService.cancel(tr.getOrderId(), pur.getPartnerCode(), pur.getSecret());
                        if (null != cancel && StringUtils.isNotBlank(cancel.getCode()) && Constant.RET_CODE_0000.equals(cancel.getCode())) {
                            log.info(pur.getDeviceCode() + "：未启用赠送套餐：" + tr.getOrderId() + "取消成功");
                        } else {
                            log.info(pur.getDeviceCode() + "：未启用赠送套餐：" + tr.getOrderId() + "取消失败，发送异常邮件");
                            if (null == cancel) {
                                //发送异常邮件：
                                purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "取消订单", "接口连接超时或其他原因导致的取消失败");
                                //记录异常操作到数据库：
                                assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "3", "9998", "程序中异常导致的失败");
                                log.info(pur.getDeviceCode() + "：【未启用赠送套餐】接口连接超时或其他原因导致的取消失败");
                            } else {
                                if (StringUtils.isNotBlank(cancel.getCode())) {
                                    //发送异常邮件：
                                    purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "取消订单", cancel.getMessage());
                                    //记录异常操作到数据库：
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "3", cancel.getCode(), cancel.getMessage());
                                    log.info(pur.getDeviceCode() + "：【未启用赠送套餐】取消失败，原因：" + cancel.getMessage());
                                } else {
                                    //发送异常邮件：
                                    purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "取消订单", "接口连接超时或其他原因导致的取消失败");
                                    //记录异常操作到数据库：
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "3", "9998", "程序中异常导致的失败");
                                    log.info(pur.getDeviceCode() + "：【未启用赠送套餐】接口连接超时或其他原因导致的取消失败");
                                }
                            }
                        }
                    } else if (b2) {
                        log.info(pur.getDeviceCode() + "：有【正在使用赠送套餐】：" + tr.getPackageName());
                        //正在使用赠送套餐----提前结束订单
                        EndResponse end = toBeijingService.end(tr.getOrderId(), pur.getPartnerCode(), pur.getSecret(), "购买新套餐时需将赠送套餐提前结束");
                        if (null != end && StringUtils.isNotBlank(end.getCode()) && Constant.RET_CODE_0000.equals(end.getCode())) {
                            log.info(pur.getDeviceCode() + "：正在使用赠送套餐：" + tr.getOrderId() + "【提前结束】成功");
                        } else {
                            log.info(pur.getDeviceCode() + "：正在使用赠送套餐：" + tr.getOrderId() + "【提前结束】失败，发送异常邮件");
                            if (null == end) {
                                //发送异常邮件：
                                purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "提前结束订单", "接口连接超时或其他原因导致的提前结束失败");
                                //记录异常操作到数据库：
                                assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", "9998", "程序中异常导致的失败");
                                log.info(pur.getDeviceCode() + "：【正在使用赠送套餐】因接口连接超时或其他原因导致的提前结束失败");
                            } else {
                                if (StringUtils.isNotBlank(end.getCode())) {
                                    //发送异常邮件：
                                    purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "提前结束订单", end.getMessage());
                                    //记录异常操作到数据库：
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", end.getCode(), end.getMessage());
                                    log.info(pur.getDeviceCode() + "：【正在使用赠送套餐】提前结束失败，原因：" + end.getMessage());
                                } else {
                                    //发送异常邮件：
                                    purchaseService.sendMail(pur.getDeviceCode(), pur.getPackageName(), tr.getOrderId(), "提前结束订单", "接口连接超时或其他原因导致的提前结束失败");
                                    //记录异常操作到数据库：
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", "9998", "程序中异常导致的失败");
                                    log.info(pur.getDeviceCode() + "：【正在使用套餐】因接口连接超时或其他原因导致的提前结束失败");
                                }
                            }
                        }
                    }
                }
            }
        }
        /*响应结果：{"code":"0027","data":null,"message":"不存在此流量套餐订单","success":false}*/
    }


    /**
     * 新的：匹配可续订订单的逻辑
     * <p>
     * 1，与正在使用订单套餐一致==续订；
     * 2，有正在使用订单，与已暂停或未启用订单套餐一致==续订；
     * 3，无正在使用订单，与已暂停或未启用订单套餐一致==续订；
     * 4，有正在使用订单，无已暂停或未启用订单==订购不立即开通
     *
     * @param orderData
     * @param pur
     * @return
     */
    public String matchRenewOrderNew(ResponseQueryDeviceOrder orderData, RequestPurchaseService pur) {
        /*orderType :订单类型：0-日程套餐订单；1-流量套餐订单；orderStatus :订单状态：0-未支付；1-未启用；2-开始使用；3-已结束；4-已取消；5-已暂停；*/
        log.info(pur.getDeviceCode() + "：开始查询【正在使用订单】");
        ResponseQueryDeviceOrder inUse = toBeijingService.queryDeviceOrder(pur.getDeviceCode(), "", "2", "", pur.getPartnerCode(), pur.getSecret());
        /*系统异常 响应：{"code":"9999","data":null,"message":null,"success":false}*/
        if (null == inUse || null == inUse.getCode() || StringOutputConstant.CODE_9999.equals(inUse.getCode())) {
            //发送异常邮件：
            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询正在使用订单", "未查询到任何套餐，请求或相应出现异常！");
            //记录异常操作到数据库：
            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", "9999", "未查询到任何套餐，请求或相应出现异常！");
            log.info(pur.getDeviceCode() + "未查询到任何套餐，请求或相应出现异常！");
            return assistService.responseStr("9999", pur.getDeviceCode() + "：未查询到任何套餐，请求或相应出现异常！");
        }
        if (Constant.RET_CODE_0000.equals(inUse.getCode()) && null != inUse.getData() && null != inUse.getData().getPackageOrder() && !inUse.getData().getPackageOrder().isEmpty()) {

            for (DevicePackageOrder tr : inUse.getData().getPackageOrder()) {

                if (StringUtils.isNotBlank(tr.getPackageCode()) && StringUtils.isNotBlank(tr.getOrderId()) && StringUtils.isNotBlank(pur.getPackageCode())) {

                    if (pur.getPackageCode().equalsIgnoreCase(tr.getPackageCode())) {
                        log.info(pur.getDeviceCode() + "：查到与【正在使用】的订单code一致：【续订】");
                        RenewResponse reNew = toBeijingService.reOrder(tr.getOrderId(), pur);
                        if (null != reNew && Constant.RET_CODE_0000.equals(reNew.getCode())) {
                            //去数据库更新isRenew和isOpen参数
                            Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "1");
                            if (c > 0) {
                                return assistService.responseStr("0000", pur.getDeviceCode() + "：请求【续订正在使用订单】成功");
                            } else {
                                //发送异常邮件：
                                purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订正在使用订单", "请求【续订正在使用订单】成功，但入库失败");
                                return assistService.responseStr("9999", pur.getDeviceCode() + "：请求【续订正在使用订单】成功，但入库失败");
                            }
                        } else {
                            if (null == reNew) {
                                //发送异常邮件：
                                purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订正在使用订单", "【续订正在使用订单】程序中异常导致的失败");
                                assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                                return assistService.responseStr("9998", pur.getDeviceCode() + "：【续订正在使用订单】失败");
                            } else {
                                if (StringUtils.isNotBlank(reNew.getCode())) {
                                    //发送异常邮件：
                                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订正在使用订单", reNew.getMessage());
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", reNew.getCode(), reNew.getMessage());
                                    return assistService.responseStr(reNew.getCode(), pur.getDeviceCode() + ":" + reNew.getMessage());
                                } else {
                                    //发送异常邮件：
                                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订正在使用订单", "【续订正在使用订单】程序中异常导致的失败");
                                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                                    return assistService.responseStr("9998", pur.getDeviceCode() + "：【续订正在使用订单】失败");
                                }
                            }
                        }
                    } else {
                        /*正在使用的订单存在，但是与现在请求的套餐编码不一致，继续去查询是不是存在相同套餐的未启用订单;orderData能走到这一步至少不可能是null*/
                        log.info(pur.getDeviceCode() + "：【有正在使用订单，再匹配未启用或暂停订单】");
                        if (null != orderData && Constant.RET_CODE_0000.equals(orderData.getCode()) && null != orderData.getData() && null != orderData.getData().getPackageOrder() && !orderData.getData().getPackageOrder().isEmpty()) {
                            //先声明一个list集合用来装符合未启用或暂停订单条件，并且与请求的套餐编码一致的订单
                            List<DevicePackageOrder> finishList = new ArrayList<>();
                            for (DevicePackageOrder t : orderData.getData().getPackageOrder()) {
                                //只允许符合条件的订单进入
                                boolean b1 = StringUtils.isNotBlank(t.getPackageCode()) && StringUtils.isNotBlank(t.getOrderId()) && StringUtils.isNotBlank(pur.getPackageCode()) && (t.getOrderStatus().equals(StringOutputConstant.CODE_ONE) || t.getOrderStatus().equals(StringOutputConstant.CODE_FIVE));
                                if (b1 && pur.getPackageCode().equals(t.getPackageCode())) {
                                    //把所有订单中符合b1条件，并且符合套餐编码一致的前提的订单add进入到finishList以便去做排序等操作
                                    finishList.add(t);
                                }
                            }
                            //如果有正在使用订单，再匹配未启用或暂停订单时，finishList集合不为空集合
                            if (!finishList.isEmpty()) {
                                //这边判断一下时间先后再决定续订哪一单,获得排序后的订单列表
                                List<DevicePackageOrder> rList = sortAsc(finishList);
                                //获取到排序后的第一条订单，也就是时间最早的订单
                                DevicePackageOrder ta = rList.get(0);
                                log.info(pur.getDeviceCode() + "：有正在使用单，但与未启用或暂停订单code一致：【续订】");
                                RenewResponse reNew = toBeijingService.reOrder(ta.getOrderId(), pur);
                                if (null != reNew && Constant.RET_CODE_0000.equals(reNew.getCode())) {
                                    //去数据库更新isRenew和isOpen参数
                                    Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "1", "1");
                                    if (c > 0) {
                                        return assistService.responseStr("0000", pur.getDeviceCode() + "：有正在使用单，同时请求【续订】成功");
                                    } else {
                                        //发送异常邮件：
                                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停单", "有正在使用订单，同时请求【续订】成功，但入库失败！");
                                        return assistService.responseStr("9999", pur.getDeviceCode() + "：有正在使用订单，同时请求【续订】成功，但入库失败！");
                                    }
                                } else {
                                    if (null == reNew) {
                                        //发送异常邮件：
                                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停单", "有正在使用订单，同时请求【续订】程序中异常导致的失败！");
                                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                                        return assistService.responseStr("9998", pur.getDeviceCode() + "：有正在使用订单，同时请求【续订】失败");
                                    } else {
                                        if (StringUtils.isNotBlank(reNew.getCode())) {
                                            //发送异常邮件：
                                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停单", reNew.getMessage());
                                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", reNew.getCode(), reNew.getMessage());
                                            return assistService.responseStr(reNew.getCode(), pur.getDeviceCode() + ":" + reNew.getMessage());
                                        } else {
                                            //发送异常邮件：
                                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停订单", "有正在使用订单，同时请求【续订】程序中异常导致的失败！");
                                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                                            return assistService.responseStr("9998", pur.getDeviceCode() + "：有正在使用订单，同时请求【续订】失败");
                                        }
                                    }
                                }
                            } else {
                                log.info(pur.getDeviceCode() + "：符合有正在使用单同时【订购但不立即开通】");
                                OrderResponse orderNew = toBeijingService.order(pur, "0");
                                if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                                    //去数据库更新isRenew和isOpen参数
                                    Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "0", "0");
                                    if (c > 0) {
                                        return assistService.responseStr("0000", pur.getDeviceCode() + "：有正在使用单同时【新订但不立即开通】成功");
                                    } else {
                                        //发送异常邮件：
                                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "新订但不立即开通", "有正在使用订单同时【新订但不立即开通】成功，但入库失败");
                                        return assistService.responseStr("9999", pur.getDeviceCode() + "：有正在使用订单同时【新订但不立即开通】成功，但入库失败");
                                    }
                                } else {
                                    //这边需要做异常处理：
                                    if (null == orderNew) {
                                        //发送异常邮件：
                                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "新订但不立即开通", "有正在使用单同时【新订但不立即开通】程序中异常导致的失败");
                                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                                        return assistService.responseStr("9998", pur.getDeviceCode() + "：【新订但不立即开通】失败");
                                    } else {
                                        if (StringUtils.isNotBlank(orderNew.getCode())) {
                                            //发送异常邮件：
                                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "新订但不立即开通", orderNew.getMessage());
                                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                                            return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                                        } else {
                                            //发送异常邮件：
                                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "新订不立即开通", "有正在使用订单同时【新订但不立即开通】程序中异常导致的失败");
                                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                                            return assistService.responseStr("9998", pur.getDeviceCode() + "：【新订不立即开通】失败");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /*响应结果：{"code":"0027","data":null,"message":"不存在此流量套餐订单","success":false}*/
        /*无正在使用的订单存在，继续去查询是不是存在相同套餐的未启用订单或者暂停订单，如果有按照时间最早续订。orderData能走到这一步至少不可能是null*/
        log.info(pur.getDeviceCode() + "：无【正在使用】订单，匹配【未启用或暂停订单】");
        if (null != orderData && Constant.RET_CODE_0000.equals(orderData.getCode()) && null != orderData.getData() && null != orderData.getData().getPackageOrder() && !orderData.getData().getPackageOrder().isEmpty()) {
            //先声明一个list集合用来装符合未启用或暂停订单条件，并且与请求的套餐编码一致的订单
            List<DevicePackageOrder> finishList = new ArrayList<>();
            for (DevicePackageOrder t : orderData.getData().getPackageOrder()) {
                boolean b1 = (StringUtils.isNotBlank(t.getPackageCode()) && StringUtils.isNotBlank(t.getOrderId()) && StringUtils.isNotBlank(pur.getPackageCode()) && (t.getOrderStatus().equals(StringOutputConstant.CODE_ONE) || t.getOrderStatus().equals(StringOutputConstant.CODE_FIVE)));
                if (b1 && pur.getPackageCode().equalsIgnoreCase(t.getPackageCode())) {
                    //把所有订单中符合b1条件，并且符合套餐编码一致的前提的订单add进入到finishList以便去做排序等操作
                    finishList.add(t);
                }
            }
            //如果无正在使用订单，再匹配未启用或暂停订单时，finishList集合不为空集合
            if (!finishList.isEmpty()) {
                //这边判断一下时间先后再决定续订哪一单
                List<DevicePackageOrder> rList = finishList;
                //获得ASC排序后的订单列表
                rList = sortAsc(rList);
                /*rList.get(0)：拿到订单列表中最早订购的那个订单*/
                DevicePackageOrder ta = rList.get(0);
                log.info(pur.getDeviceCode() + "：无正在使用订单，存在未启用或者暂停订单code一致：【续订】");
                RenewResponse reNew = toBeijingService.reOrder(ta.getOrderId(), pur);
                if (null != reNew && Constant.RET_CODE_0000.equals(reNew.getCode())) {
                    //去数据库更新isRenew和isOpen参数
                    Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "1", "1");
                    if (c > 0) {
                        return assistService.responseStr("0000", pur.getDeviceCode() + "：无正在使用单，存在未启用或者暂停订单code一致，【续订】成功");
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停订单", "无正在使用单，存在未启用或者暂停订单code一致，【续订】成功,但入库失败");
                        return assistService.responseStr("9999", pur.getDeviceCode() + "：无正在使用订单，存在未启用或者暂停订单code一致，【续订】成功,但入库失败");
                    }
                } else {
                    if (null == reNew) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停订单", "无正在使用单，存在未启用或者暂停订单code一致，【续订】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：无正在使用单，存在未启用或者暂停订单code一致，【续订】失败");
                    } else {
                        if (StringUtils.isNotBlank(reNew.getCode())) {
                            //发送异常邮件：
                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停订单", reNew.getMessage());
                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", reNew.getCode(), reNew.getMessage());
                            return assistService.responseStr(reNew.getCode(), pur.getDeviceCode() + ":" + reNew.getMessage());
                        } else {
                            //发送异常邮件：
                            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "续订未启用或者暂停订单", "无正在使用单，存在未启用或者暂停订单code一致，【续订】程序中异常导致的失败");
                            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "2", "9998", "程序中异常导致的失败");
                            return assistService.responseStr("9998", pur.getDeviceCode() + "：无正在使用单，存在未启用或者暂停订单code一致，【续订】失败");
                        }
                    }
                }
            }
        }
        //如果以上所有情况都不满足，那么就只能符合新订的流程了，给上一级返回一个“FAIL”让程序继续往下走
        log.info(pur.getDeviceCode() + "：符合新订流程");
        return StringOutputConstant.CODE_FAIL;
    }


    /**
     * 新的：匹配新订订单的逻辑
     * <p>
     * 先查设备，再匹配订单记录
     * <p>
     * 1，设备是ota卡==订购不立即开通
     * 2，设备无订单==订购立即开通
     *
     * @param pur
     * @return
     */
    public String matchOrderNew(RequestPurchaseService pur) {
        log.info(pur.getDeviceCode() + "：流量套餐新订逻辑：" + pur.getPackageType());
        /*续订规则都走不通时，走新订，但是流量套餐新订时要不要立即开通要根据是否为OTA决定：在这边先判断一下卡片是ota还是非ota卡片*/
        ResponseQueryDevice device = toBeijingService.queryDevice(pur.getDeviceCode().trim(), pur.getPartnerCode(), pur.getSecret());
        if (null == device || !Constant.RET_CODE_0000.equals(device.getCode()) || null == device.getData() || StringUtils.isBlank(device.getData().getDevice_id()) || StringUtils.isBlank(device.getData().getOta_flag())) {
            if (null == device) {
                //发送异常邮件：
                purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询设备是否是OTA卡", "【查询设备是否为OTA】程序中异常导致的失败");
                assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "5", "9998", "程序中异常导致的失败");
                return assistService.responseStr("9998", pur.getDeviceCode() + "：【查询设备是否是OTA卡】失败，程序终止！");
            } else {
                if (StringUtils.isNotBlank(device.getCode())) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询设备是否是OTA卡", device.getMessage());
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "5", device.getCode(), device.getMessage());
                    return assistService.responseStr(device.getCode(), pur.getDeviceCode() + ":" + device.getMessage());
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询设备是否是OTA卡", "【查询设备是否为OTA】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "5", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：【查询设备是否是OTA卡】失败，程序终止！");
                }
            }
        }
        /*otaFlag:是否有OTA功能，取值如下：1-有OTA功能；2-没有OTA功能*/
        if (StringOutputConstant.CODE_ONE.equals(device.getData().getOta_flag())) {
            log.info(pur.getDeviceCode() + "：符合OTA卡【订购不立即开通】");
            OrderResponse orderNew = toBeijingService.order(pur, "0");
            if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                //去数据库更新isRenew和isOpen参数 （ota的卡片接口永远起不来，所以这边直接设为不用启用的1）
                Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "1");
                if (c > 0) {
                    return assistService.responseStr("0000", pur.getDeviceCode() + "：OTA卡【订购不立即开通】成功");
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "OTA卡：【订购不立即开通】", "OTA卡【订购不立即开通】成功，但入库失败");
                    return assistService.responseStr("9999", pur.getDeviceCode() + "：OTA卡【订购不立即开通】成功，但入库失败");
                }
            } else {
                //这边需要做异常处理：
                if (null == orderNew) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "OTA卡：【订购不立即开通】", "OTA卡【订购不立即开通】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：OTA卡【订购不立即开通】失败");
                } else {
                    if (StringUtils.isNotBlank(orderNew.getCode())) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "OTA卡：【订购不立即开通】", orderNew.getMessage());
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                        return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "OTA卡：【订购不立即开通】", "OTA卡【订购不立即开通】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：OTA卡【订购不立即开通】失败");
                    }
                }
            }
        }

        /*设备是非ota设备：然后再次查全部订单*/
        log.info(pur.getDeviceCode() + "：再次查询【所有订单】");
        ResponseQueryDeviceOrder order = toBeijingService.queryDeviceOrder(pur.getDeviceCode(), "", "", "", pur.getPartnerCode(), pur.getSecret());
        /*系统异常 响应：{"code":"9999","data":null,"message":null,"success":false}*/
        if (null == order || null == order.getCode() || StringOutputConstant.CODE_9999.equals(order.getCode())) {
            //发送异常邮件：
            purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "查询全部订单", "未查询到任何套餐，请求或相应出现异常！");
            //记录异常操作到数据库：
            assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode(), pur.getPayId(), pur.getOrderNo(), "4", "9999", "未查询到任何套餐，请求或相应出现异常！");
            log.info(pur.getDeviceCode() + "未查询到任何套餐，请求或相应出现异常！");
            return assistService.responseStr("9999", pur.getDeviceCode() + "：未查询到任何套餐，请求或相应出现异常！");
        }

        /*1，如果卡片上一个订单都没有【订购立即开通】;响应结果：{"code":"0027","data":null,"message":"不存在此流量套餐订单","success":false}*/
        if (StringOutputConstant.CODE_0027.equals(order.getCode()) || null == order.getData() || null == order.getData().getPackageOrder() || order.getData().getPackageOrder().isEmpty()) {
            log.info(pur.getDeviceCode() + "：无订单【订购立即开通】");
            OrderResponse orderNew = toBeijingService.order(pur, "1");
            if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                //去数据库更新isRenew和isOpen参数 （ota的卡片接口永远起不来，所以这边直接设为不用启用的1）
                Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "1");
                if (c > 0) {
                    return assistService.responseStr("0000", pur.getDeviceCode() + "：无订单【订购立即开通】成功");
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无订单：【订购立即开通】", "OTA卡【订购立即开通】成功，但入库失败");
                    return assistService.responseStr("9999", pur.getDeviceCode() + "：无订单【订购立即开通】成功，但入库失败");
                }
            } else {
                //这边需要做异常处理：
                if (null == orderNew) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无订单：【订购立即开通】", "无订单【订购立即开通】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：无订单【订购立即开通】失败");
                } else {
                    if (StringUtils.isNotBlank(orderNew.getCode())) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无订单：【订购立即开通】", orderNew.getMessage());
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                        return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无订单：【订购立即开通】", "无订单【订购立即开通】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：无订单【订购立即开通】失败");
                    }
                }
            }
        }

        /*开始遍历订单*/
        List<String> statusList = new ArrayList<>();
        for (DevicePackageOrder tr : order.getData().getPackageOrder()) {
            statusList.add(tr.getOrderStatus());
        }

        /*2,如果卡片上一个有效订单都没有【订购立即开通】*/
        boolean b1 = (statusList.contains(StringOutputConstant.CODE_ONE)) || (statusList.contains(StringOutputConstant.CODE_TWO)) || (statusList.contains(StringOutputConstant.CODE_FIVE));
        if (!b1) {
            log.info(pur.getDeviceCode() + "：无有效订单【订购立即开通】");
            OrderResponse orderNew = toBeijingService.order(pur, "1");
            if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                //去数据库更新isRenew和isOpen参数 （ota的卡片接口永远起不来，所以这边直接设为不用启用的1）
                Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "1");
                if (c > 0) {
                    return assistService.responseStr("0000", pur.getDeviceCode() + "：无有效订单【订购立即开通】成功");
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无有效订单：【订购立即开通】", "无有效订单【订购立即开通】成功，但入库失败");
                    return assistService.responseStr("9999", pur.getDeviceCode() + "：无有效订单【订购立即开通】成功，但入库失败");
                }
            } else {
                //这边需要做异常处理：
                if (null == orderNew) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无有效订单：【订购立即开通】", "无有效订单【订购立即开通】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：无有效订单【订购立即开通】失败");
                } else {
                    if (StringUtils.isNotBlank(orderNew.getCode())) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无有效订单：【订购立即开通】", orderNew.getMessage());
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                        return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "无有效订单：【订购立即开通】", "无有效订单【订购立即开通】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：无有效订单【订购立即开通】失败");
                    }
                }
            }
        }

        /*3，理论上这里是：有未启用或者已暂停订单的情况*/
        List<DevicePackageOrder> orderList = sortAsc(order.getData().getPackageOrder());
        /*4，做法：匹配时间最早的订单*/
        DevicePackageOrder or = orderList.get(0);
        /*5,如果最早的订单是未启用状态，就认为是首单未启用==【订购不立即启用】*/
        if (StringOutputConstant.CODE_ONE.equals(or.getOrderStatus())) {
            log.info(pur.getDeviceCode() + "：首单未启用【订购不立即启用】");
            OrderResponse orderNew = toBeijingService.order(pur, "0");
            if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                //去数据库更新isRenew和isOpen参数 （ota的卡片接口永远起不来，所以这边直接设为不用启用的1）
                Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "0");
                if (c > 0) {
                    return assistService.responseStr("0000", pur.getDeviceCode() + "：首单未启用【订购不立即启用】成功");
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单未启用：【订购不立即启用】", "首单未启用【订购不立即启用】成功，但入库失败");
                    return assistService.responseStr("9999", pur.getDeviceCode() + "：首单未启用【订购不立即启用】成功，但入库失败");
                }
            } else {
                //这边需要做异常处理：
                if (null == orderNew) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单未启用：【订购不立即启用】", "首单未启用【订购不立即启用】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：首单未启用【订购不立即启用】失败");
                } else {
                    if (StringUtils.isNotBlank(orderNew.getCode())) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单未启用：【订购不立即启用】", orderNew.getMessage());
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                        return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单未启用：【订购不立即启用】", "首单未启用【订购不立即启用】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：首单未启用【订购不立即启用】失败");
                    }
                }
            }

        }

        /*6,如果最早的订单不是未启用状态，就认为是首单已启过可以启其他的订单==【订购立即启用】*/
        log.info(pur.getDeviceCode() + "：首单无效【订购立即启用】");
        OrderResponse orderNew = toBeijingService.order(pur, "1");
        if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
            //去数据库更新isRenew和isOpen参数 （ota的卡片接口永远起不来，所以这边直接设为不用启用的1）
            Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "1");
            if (c > 0) {
                return assistService.responseStr("0000", pur.getDeviceCode() + "：首单无效【订购立即启用】成功");
            } else {
                //发送异常邮件：
                purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单无效【订购立即启用】", "首单无效【订购立即启用】成功，但入库失败");
                return assistService.responseStr("9999", pur.getDeviceCode() + "：首单无效【订购立即启用】成功，但入库失败");
            }
        } else {
            //这边需要做异常处理：
            if (null == orderNew) {
                //发送异常邮件：
                purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单无效【订购立即启用】", "首单无效【订购立即启用】程序中异常导致的失败");
                assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                return assistService.responseStr("9998", pur.getDeviceCode() + "：首单无效【订购立即启用】失败");
            } else {
                if (StringUtils.isNotBlank(orderNew.getCode())) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单无效【订购立即启用】", orderNew.getMessage());
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                    return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "首单无效【订购立即启用】", "首单无效【订购立即启用】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：首单无效【订购立即启用】失败");
                }
            }
        }
    }


    /**
     * 匹配请求上来的套餐类型
     * <p>
     * 日程类套餐：特殊处理，订购不立即开通
     *
     * @param pur
     * @return
     */
    private String matchPackageType(RequestPurchaseService pur) {
        /*新订要不要开通中日程类套餐是个特例。这边对日程类套餐进行特殊处理，不允许订购并立即开通,订购之后也不需要手动开通 */
        if (StringOutputConstant.CODE_ZERO.equals(pur.getPackageType())) {
            log.info(pur.getDeviceCode() + "：日程类套餐订购且不允许立即开通:" + pur.getPackageType());
            OrderResponse orderNew = toBeijingService.order(pur, "0");
            if (null != orderNew && Constant.RET_CODE_0000.equals(orderNew.getCode())) {
                /*去数据库更新isRenew和isOpen参数*/
                Integer c = assistService.updateOrderByOrderNo(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo().trim(), "0", "1");
                if (c > 0) {
                    return assistService.responseStr("0000", pur.getDeviceCode() + "：日程类套餐【订购不立即开通】成功");
                } else {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "日程类套餐：【订购不立即开通】", "日程套餐：【订购不立即开通】成功，但入库失败");
                    return assistService.responseStr("9999", pur.getDeviceCode() + "：日程类套餐：【订购不立即开通】成功，但入库失败");
                }
            } else {
                /*这边需要做异常处理*/
                if (null == orderNew) {
                    //发送异常邮件：
                    purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "日程类套餐【订购不立即开通】", "日程套餐：【订购不立即开通】程序中异常导致的失败");
                    assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                    return assistService.responseStr("9998", pur.getDeviceCode() + "：日程类套餐：【订购不立即开通】失败");
                } else {
                    if (StringUtils.isNotBlank(orderNew.getCode())) {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "日程类套餐【订购不立即开通】", orderNew.getMessage());
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", orderNew.getCode(), orderNew.getMessage());
                        return assistService.responseStr(orderNew.getCode(), pur.getDeviceCode() + ":" + orderNew.getMessage());
                    } else {
                        //发送异常邮件：
                        purchaseService.sendMailToPrivate(pur.getDeviceCode(), pur.getPackageName(), "日程类套餐【订购不立即开通】", "日程套餐：【订购不立即开通】程序中异常导致的失败");
                        assistService.exceptionDetailsRecord(pur.getPartnerCode(), pur.getDeviceCode().trim(), pur.getPayId().trim(), pur.getOrderNo(), "1", "9998", "程序中异常导致的失败");
                        return assistService.responseStr("9998", pur.getDeviceCode() + "：日程类套餐：【订购不立即开通】失败");
                    }
                }
            }
        }
        /*套餐不是日程类套餐，是流量套餐*/
        return StringOutputConstant.CODE_FAIL;
    }

    /***
     * 按照时间从最早到最晚将订单排序
     *
     * 订单时间ASC排序
     *
     * @param rList
     * @return
     */
    public List<DevicePackageOrder> sortAsc(List<DevicePackageOrder> rList) {
        /*不加.reversed()是正序排序Asc*/
        List<DevicePackageOrder> listAsc = rList.stream().sorted(Comparator.comparing(DevicePackageOrder::getOrderDate)).collect(Collectors.toList());
        log.info(String.format("按照时间从最早到最晚将订单排序：%s", listAsc));
        /*.reversed()是倒叙排序Desc ：按照时间从最新到最早将订单排序 List<DevicePackageOrder> listDesc = rList.stream().sorted(Comparator.comparing(DevicePackageOrder::getOrderDate).reversed()).collect(Collectors.toList());*/
        return listAsc;

    }
}
